# coding:utf8
"""从邮件接受指令并回复
    1. 监控邮箱，显示最新获取的邮件 并 解析
    2. 更具邮件的内容 做出相应的响应

    2019.10.29 -> 完成 e_mail.receive.cl_receive_mail & e_mail.send.cl_send_mail 的构建。
    2019.10.30 -> 完成 mainloop & send ip 建构。
"""
import sys

sys.path.extend(['C:\\Py',
                 'C:\\Py\\WiFi',
                 'C:\\Py\\Python',
                 'C:\\Py\\study',
                 'C:\\Py\\e_mail',
                 'C:\\Py\\IO_file',
                 ])

import poplib
import email
import time
import os
from e_mail.send.cl_send_mail import SendMail
from e_mail.receive.cl_receive_mail import ReceiveMail
from e_mail import command

# ----- 全局变量 ------
SEND_LIST = ['lee_cq@icloud.com', '670343981@qq.com', ]
_DEBUGING = 0
CRLF = '\r\n'
bCRLF = b'\t\n'


def get_new_mail(_dic, second=5):
    t = ReceiveMail(**_dic)
    now_count = t.get_mail_quantity()
    print('开启的时候的邮件数量为:%s' % now_count)
    # 每次需要重新连接邮箱服务器，才能获取到最新的消息
    # 默认每隔5秒看一次是否有新内容
    while True:
        obj = ReceiveMail(**_dic)
        count = obj.get_mail_quantity()
        if _DEBUGING == 1:
            mail = obj.get_new_mail()
            yield {"subject": mail[0], "sender": mail[1], "body": mail[2]}
        if count > now_count:
            new_mail_count = count - now_count
            print('有新的邮件数量:%s' % new_mail_count)
            for i in range(1, new_mail_count + 1):
                obj = ReceiveMail(**_dic)
                now_count += 1
                mail = obj.get_one_mail(now_count)

                # yield mail
                yield {"subject": mail[0], "sender": mail[1], "body": mail[2]}
                # print('-' * 30)
                # print("邮件主题:%s\n发件人:%s\n发件人邮箱:%s\n邮件内容:%s" % (
                #     obj.email_title, obj.sender_qq_name, obj.sender_qq_email, obj.email_content))
                # print('-' * 30)

        # else:
        #     print('没有任何新消息.')

        time.sleep(second)


def main():
    dic = {'pop_host': 'pop.qq.com',
           'smtp_host': 'smtp.qq.com',
           'user': '1491311784@qq.com',
           'passwd': 'llfgameckwovhbea',
           }
    print(f"接收邮箱:{dic['user']}")
    print('正在监听邮件服务器端是否有新消息---')
    try:
        iterator = get_new_mail(dic)  # 创建了一个可迭代的对象 -> iterator
    except TypeError and AttributeError:
        print('监听的内容有误，有图片数据等,无法解析而报错，不是纯文本内容')
    else:
        for _dic in iterator:
            print('-' * 30)
            print("邮件主题:%s\n发件人邮箱:%s\n邮件内容:%s" % (_dic["subject"], _dic["sender"], _dic['body']))
            print('-' * 30)
            if _dic['subject'] == 'command' and _dic['sender'] in SEND_LIST:
                command_list = _dic['body'].split(CRLF)

                if 'send ip' in command_list: command.SendIP(**dic, receive=_dic['sender'])
                if 'send data usage' in command_list: pass

                # shutdown
                if ('shutdown now' or 'shutdown') in command_list: command.Shutdown().at_now()
                if 'shutdown off' in command_list: os.system('shutdown /a')


if __name__ == "__main__":
    
    main()
